package com.caowei.weicimpress.weicimpress.widget;

import android.content.Context;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by caoweiPc on 2014/7/17.
 */
public abstract class DialogWidget extends PopupWindow {
    private static final int MEASURE_AND_LAYOUT_DONE = 1 << 1;
    private List<ActionItem> mActionItems=new ArrayList<ActionItem>();
    private int mScreenHeight;
    private int mScreenWidth;
    private Context mContext;
    private boolean mIsDirty;
    private int[] mLocation =new int[2];
    private final Rect mRect = new Rect();
    private int mPrivateFlags;
    private int mPopupY;
    private int mPopupX;
    private boolean mIsOnTop;
    private boolean mIsOnLeft;

    public DialogWidget(Context context){
        super(context);
        mContext = context;

        setFocusable(true);
        setTouchable(true);
        setOutsideTouchable(true);
        setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

        final WindowManager windowManager = (WindowManager)
                mContext.getSystemService(Context.WINDOW_SERVICE);
        mScreenWidth = windowManager.getDefaultDisplay().getWidth();
        mScreenHeight = windowManager.getDefaultDisplay().getHeight();
    }

    public void setContentView(int layoutId) {
        setContentView(LayoutInflater.from(mContext).inflate(layoutId, null));
    }

    public ActionItem getActionItem(int position) {
        if(position < 0 || position >= mActionItems.size()) return null;
        return mActionItems.get(position);
    }

    protected int getScreenWidth() {
        return mScreenWidth;
    }

    public Context getContext( ){
        return this.mContext;
    }

    /**
     * Returns the height of the screen.
     *
     * @return The height of the screen
     */
    protected int getScreenHeight() {
        return mScreenHeight;
    }

    public void addActionItem(ActionItem action) {
        if (action != null) {
            mActionItems.add(action);
            mIsDirty = true;
        }
    }

    public void clearAllActionItem() {
        if (!mActionItems.isEmpty()) {
            mActionItems.clear();
            mIsDirty = true;
        }
    }

    protected void clearActionItems() {
        if (!mActionItems.isEmpty()) {
            onClearActionItems();
        }
    }

    protected void onClearActionItems() {
    }

    protected void prepareShow(View anchor){
        final View contentView = getContentView();
        if (contentView == null) {
            throw new IllegalStateException("You need to set the content view using the setContentView method");
        }
        //设置触摸事件 - 修复触摸弹窗以外的地方无法隐藏弹窗
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int x = (int) event.getX();
                final int y = (int) event.getY();

                if ((event.getAction() == MotionEvent.ACTION_DOWN)
                        && ((x < 0) || (x >= getWidth()) || (y < 0) || (y >= getHeight()))) {
                    dismiss();
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    dismiss();
                    return true;
                } else {
                    return contentView.onTouchEvent(event);
                }
            }
        });

        // Replaces the background of the popup with a cleared background
        //setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //修复点击背景空白
        setBackgroundDrawable(null);
        final int[] loc = mLocation;
        anchor.getLocationOnScreen(loc);
        mRect.set(loc[0], loc[1], loc[0] + anchor.getWidth(), loc[1] + anchor.getHeight());
        if (mIsDirty) {
            clearActionItems();
            populateActionItems(mActionItems);
        }
        onMeasureAndLayout(mRect, contentView);

        if ((mPrivateFlags & MEASURE_AND_LAYOUT_DONE) != MEASURE_AND_LAYOUT_DONE) {
            throw new IllegalStateException("onMeasureAndLayout() did not set the widget specification by calling"
                    + " setWidgetSpecs()");
        }
        prepareAnimationStyle();
    }

    public void show(View anchor) {
        prepareShow(anchor);
        showAtLocation(anchor, Gravity.NO_GRAVITY, mPopupX, mPopupY);
        afterShow();
    }


    public void show(View anchor,int popupY) {
        prepareShow(anchor);
        if(mPopupY!=popupY){
            mPopupY=popupY;
        }
        showAtLocation(anchor, Gravity.NO_GRAVITY, mPopupX, mPopupY);
        afterShow();
    }

    protected abstract void afterShow();


    protected void setWidgetSpecs(int popupY, boolean isOnTop,int popupX,boolean mIsOnLeft) {
        mPopupY = popupY;
        this.mIsOnTop = isOnTop;
        this.mIsOnLeft=mIsOnLeft;
        this.mPopupX=popupX;
        mPrivateFlags |= MEASURE_AND_LAYOUT_DONE;
    }

    private void prepareAnimationStyle() {
        final int screenWidth = mScreenWidth;
        final boolean onTop = mIsOnTop;
        final int arrowPointX = mRect.centerX();

 /*       if (arrowPointX <= screenWidth / 4) {
            setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Left
                    : R.style.GreenDroid_Animation_PopDown_Left);
        } else if (arrowPointX >= 3 * screenWidth / 4) {
            setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Right
                    : R.style.GreenDroid_Animation_PopDown_Right);
        } else {
            setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Center
                    : R.style.GreenDroid_Animation_PopDown_Center);
        }*/
    }

    protected void setMisDirty(boolean misDirty){
        this.mIsDirty=misDirty;
    }


    protected abstract void populateActionItems(List<ActionItem> actionItems);
    protected abstract void onMeasureAndLayout(Rect anchorRect, View contentView);
}
